package com.gift.recommendation.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zzh <2658137258@qq.com>
 * @date 2022/11/4
 */

/**
 * 拦截器，拦截所有接口
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Value("${uploadImg}")
    private String uploadPathImg;
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new UserLoginInterceptor())
                .addPathPatterns("/**").excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","/error",
                        "/uploadImg/**");
    }

    //配置图片上传地址
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //修改tomcat 虚拟映射
        registry.addResourceHandler("/uploadImg/**")
                .addResourceLocations("file:"+uploadPathImg); //定义图片存放路径
    }

    //配置跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("Content-Type","X-Requested-With","accept,Origin","Access-Control-Request-Method","Access-Control-Request-Headers","token")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowCredentials(true);
    }
}
